package com.audaque.encoding.util;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

/**
 * @author MaYong
 * @since 2023/3/20 14:17
 */
@Slf4j
@UtilityClass
public class HttpUtil {

    public static <T> T postBody(RestTemplate restTemplate, String url, HttpHeaders headers, String json, Class<T> clazz) {
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(json, headers);
        ResponseEntity<T> response = restTemplate.postForEntity(url, request, clazz);
        if (response.getStatusCode().value() != 200) {
            log.error("请求发生异常, 返回码: " + response.getStatusCode().value());
        }
        return response.getBody();

    }
    public static <T> T get(RestTemplate restTemplate,String url, HttpHeaders headers, Class<T> clazz) {
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(headers);
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, request, clazz);
        if (response.getStatusCode().value() != 200) {
            log.error("请求发生异常, 返回码: " + response.getStatusCode().value());
        }
        return response.getBody();
    }

    public static byte[] getFile(RestTemplate restTemplate,String url, HttpHeaders headers) {
        HttpEntity<String> request = new HttpEntity<>(headers);
        ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, request, byte[].class);
        if (response.getStatusCode().value() != 200) {
            log.error("请求发生异常, 返回码: " + response.getStatusCode().value());
        }
        return response.getBody();
    }




    public static <T> void put(RestTemplate restTemplate,String url, HttpHeaders headers) {
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        HttpEntity<String> request = new HttpEntity<>( headers);
        restTemplate.put(url, request);
    }

    public static <T> void putBody(RestTemplate restTemplate, String url, HttpHeaders headers, byte[] file) {
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        HttpEntity<byte[]> request = new HttpEntity<>(file, headers);
        restTemplate.put(url, request);
    }

}
